package io.snow.mybatis.core.common;

import com.alibaba.fastjson.JSON;

import java.io.Serializable;
import java.util.Objects;

public class Result<T> implements Serializable {

    private Integer code;
    private String msg;
    private T data;

    Result() {}

    private Result(ResultCode resultCode) {
        this.code = resultCode.getCode();
        this.msg = resultCode.getMsg();
    }

    private Result(ResultCode resultCode, String msg) {
        this.code = resultCode.getCode();
        this.msg = msg;
    }

    private Result(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public String getMsg() { return  msg; }

    public Integer getCode() { return code; }

    public static Result noAuth() { return error(SystemCodeEnum.SYSTEM_NO_AUTH); }

    public static <T> Result<T> error (ResultCode resultCode) {
        return new Result<>(resultCode);
    }

    public static Result error(int code, String msg) {
        return new Result(code,msg);
    }

    public static Result error(ResultCode resultCode, String msg) {
        return new Result(resultCode, msg);
    }

    public static <T> Result<T> ok(T data) {
        Result<T> result = new Result<T>(SystemCodeEnum.SYSTEM_OK);
        result.setData(data);
        return result;
    }

    public static <T> Result ok() {
        return new Result(SystemCodeEnum.SYSTEM_OK);
    }

    public boolean hasSuccess() {
        return Objects.equals(SystemCodeEnum.SYSTEM_OK.getCode(),code);
    }

    public String toJSONString() {
        return JSON.toJSONString(this);
    }

    public String toString() {
        return JSON.toJSONString(this);
    }

    public T getData() {
        return this.data;
    }

    public Result setData(T data) {
        this.data = data;
        return this;
    }
}
